package com.ys168.gam.searcher;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.ys168.gam.bean.EngineInfo;
import com.ys168.gam.bean.JobInfo;
import com.ys168.gam.bean.SearchConditionInfo;
import com.ys168.gam.util.ConfigLoader;

/**
 * @author Jason Krebs
 * @since 2015年6月9日
 */
public class SearcherFactory {

    private BaseSearcher searcher;

    public SearcherFactory(String engineCode, SearchConditionInfo searchConditionInfo) {
        if (engineCode == null) {
            throw new IllegalArgumentException("engineCode");
        }
        searcher = createSearcher(engineCode, searchConditionInfo);
    }

    private BaseSearcher createSearcher(String engineCode, SearchConditionInfo searchConditionInfo) {
        EngineInfo engineInfo = ConfigLoader.getEngineInfo(engineCode);
        String searcherClazz = engineInfo.getSearcherClazz();

        try {
            @SuppressWarnings("unchecked")
            Class<? extends BaseSearcher> clazz = (Class<? extends BaseSearcher>) Class.forName(searcherClazz);
            return clazz.getConstructor(EngineInfo.class, SearchConditionInfo.class).newInstance(engineInfo,
                    searchConditionInfo);

        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<JobInfo> search() throws Exception {
        if (searcher == null) {
            return new ArrayList<JobInfo>();
        }
        List<JobInfo> jobs = new ArrayList<JobInfo>();

        int index = 0;
        for (URL url : searcher.search()) {
            jobs.add(new JobInfo(index++, url));
        }
        return jobs;
    }

}
